#encoding: utf-8
from django import forms
from apps.forms import FormMixin
from django.core.cache import cache
from .models import User

class loginForms(forms.Form,FormMixin):
    telephone = forms.CharField(max_length=11,error_messages={'max_length':'号码输入有误，手机号码必须为11位'})
    password = forms.CharField(max_length=20,min_length=6,error_messages={'max_length':'密码最多不能超过20位','min_length':'密码最少6位'})
    remember = forms.IntegerField(required=False)

# 验证注册提交的数据
class RegisterForm(forms.Form,FormMixin):
    telephone = forms.CharField(max_length=11, error_messages={'max_length': '号码输入有误，手机号码必须为11位'})
    username = forms.CharField(max_length=20)
    password1 = forms.CharField(max_length=20, min_length=6,
                               error_messages={'max_length': '密码最多不能超过20位', 'min_length': '密码最少6位'})
    password2 = forms.CharField(max_length=20, min_length=6,
                               error_messages={'max_length': '密码最多不能超过20位', 'min_length': '密码最少6位'})
    sms_captcha = forms.CharField(max_length=4,min_length=4)
    img_captcha = forms.CharField(max_length=4,min_length=4)

    # 重写clean方法
    def clean(self):
        # 获取父类的clean返回的cleaned_data
        cleaned_data = super(RegisterForm, self).clean()
        # 获clean_data里的密码
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')

        # 判断两次密码是否一致

        if password1 != password2:
            raise forms.ValidationError('两次密码输入不一致！')

        # 判断缓存中的图形验证码和输入的是否一致

        img_captcha = cleaned_data.get('img_captcha')

        # 获取缓存中的图形验证码
        cached_img_captcha = cache.get(img_captcha)

        # 假如缓存中没有，或者缓存中和输入的不一致
        if not cached_img_captcha or cached_img_captcha.lower() != img_captcha.lower():
            raise forms.ValidationError('图形验证码错误！')

        # 判断缓存中的手机验证码和输入的手机验证码是否一致

        telephone = cleaned_data.get('telephone')
        sms_cache = cleaned_data.get("sms_captcha")
        print(sms_cache)
        # 因为缓存中是根据电话来存储手机验证码的，所以要用手机号来取出
        cached_sms_captcha = cache.get(telephone)
        if not cached_sms_captcha or cached_sms_captcha.lower() != sms_cache.lower():
            raise forms.ValidationError('手机验证码错误！')

        # 判断手机号是否被注册

        # 搜索数据库用户中是否有号码和输入的一致
        exists = User.objects.filter(telephone=telephone).exists()
        if exists:
            raise forms.ValidationError('该手机号码已经被注册！')
        return cleaned_data
